package com.xgc.erp.order.purchase.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.xgc.common.base.BaseController;
import com.xgc.common.config.Constan;
import com.xgc.common.model.*;
import com.xgc.common.visit.Visitor;
import com.xgc.common.vo.Feedback;
import com.xgc.erp.order.purchase.service.PurchaseOrderService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@ControllerBind(path = "/erp/order/purchase")
public class PurchaseOrderController extends BaseController {


    @Inject
    PurchaseOrderService service;

    public void index() {
        render("index.html");
    }

    /**
     * 表格数据
     */
    public void list(){
        Record record = new Record();
        String sql = Db.getSql("erp.getPurchaseList");
        renderJson(service.queryForList(sql,getParaToInt("pageNumber",1), getParaToInt("pageSize",10),record,"order by create_time desc"));
    }

    /**
     * 新增页面
     */
    public void add() {
        setAttr("orderStatusMap", Constan.ORDER_STATUS_MAP);
        setAttr("orderContainBillMap",Constan.ORDER_CONTAIN_BILL_MAP);
        setAttr("orderSettleWayMap",Constan.ORDER_SETTLE_WAY_MAP);
        render("add.html");
    }

    public void save(){
        PurchaseOrder order = getBean(PurchaseOrder.class);
        order.setOrderId(service.getPrimaryKey(Constan.SEQ_PURCHASE_ORDER));
        order.setStatus(Constan.STATUS_1000);
        Visitor vs = getVisitor();
        order.setCreator(vs.getCode());
        order.setCreateTime(new Date());
        if(!order.save()){
            setException("数据插入失败");
        }
        render("add.html");
    }

    /**
     * 编辑页面
     */
    public void edit(){
        String orderId = get("orderId");
        Record record = new Record();
        record.set("order_id",orderId);
        PurchaseOrder purchaseOrder = (PurchaseOrder)service.findById(orderId);
        setAttr("purchaseOrder", purchaseOrder);
        setAttr("orderStatusMap", Constan.ORDER_STATUS_MAP);
        render("edit.html");
    }

    public void update(){
        PurchaseOrder order = getBean(PurchaseOrder.class);
        Visitor vs = getVisitor();
        order.setModifier(vs.getCode());
        order.setUpdateTime(new Date());
        if(!order.update()){
            setException("数据插入失败");
        }
        render("edit.html");
    }

    /**
     * 采购单预览
     */
    public void review(){
        String orderId = get("orderId");
        PurchaseOrder order = (PurchaseOrder)service.findById(orderId);
        setAttr("order", order);
        render("review.html");
    }

    public void delete() {
        service.deleteByIds(getIds());
        renderJson(Feedback.success());
    }

    /**
     * 通过,支持批量操作
     */
    public void approve(){
        List<String> ids = getIds();
        List<Integer> idList = new ArrayList<>();
        for(String id:ids){
            idList.add(Integer.parseInt(id));
        }
        Visitor vs = getVisitor();
        service.modifyStatus(idList,Constan.STATUS_1002,vs.getCode());
        renderJson(Feedback.success());
    }

    /**
     * 退回，支持批量操作
     */
    public void refuse(){
        List<String> ids = getIds();
        List<Integer> idList = new ArrayList<>();
        for(String id:ids){
            idList.add(Integer.parseInt(id));
        }
        Visitor vs = getVisitor();
        service.modifyStatus(idList,Constan.STATUS_1003,vs.getCode());
        renderJson(Feedback.success());
    }

    public void saveOrder(){
        HttpServletRequest request = getRequest();
        String supplierId = request.getParameter("supplierId");// 供应商ID
        Date planTime = getDate("planTime",new Date());// 计划到货时间
        Date actualTime = getDate("actualTime",new Date());// 实际到货时间
        String originator = get("originator","");// 开单人
        Date originatTime = getDate("originatTime",new Date());// 开单时间
        String settleWay = get("settleWay","0");//结算方式
        Double totalAmount = Double.parseDouble(get("totalAmount","0")); // 总金额
        String containBill = get("containBill","0");                // 是否含税
        Double taxRate = Double.parseDouble(get("taxRate","0"));    // 税率
        String logisticsNum = get("logisticsNum",""); // 物流编号
        Double carriage = Double.parseDouble(get("carriage","0")); // 运费
        String status = "1000";
        String creator = getVisitor().getCode();
        Date createTime = new Date();

        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setOrderId(service.getPrimaryKey(Constan.SEQ_PURCHASE_ORDER))
                .setSupplierId(supplierId).setOriginator(originator).setSettleWay(settleWay)
                .setTotalAmount(totalAmount).setContainBill(containBill).setTaxRate(taxRate)
                .setLogisticsNum(logisticsNum).setCarriage(carriage).setStatus(status)
                .setOriginatTime(originatTime).setPlanTime(planTime).setActualTime(actualTime)
                .setCreateTime(createTime).setCreator(creator);

        // 获取订单项信息
        String jsonStr = request.getParameter("detailList");
        JSONArray res = JSON.parseArray(jsonStr);
        List<PurchaseDetail> details = res.toJavaList(PurchaseDetail.class);

        // 支付列表
        String json = request.getParameter("payList");
        res = JSON.parseArray(json);
        List<OutcomeDetail> outcomeDetails = res.toJavaList(OutcomeDetail.class);

        // 事务处理
        boolean flag = Db.tx( () -> {
            if(!purchaseOrder.save()) return false;
            for (PurchaseDetail detail:details){
                detail.setDetailId(service.getPrimaryKey(Constan.SEQ_PURCHASE_DETAIL))
                        .setOrderId(purchaseOrder.getOrderId())
                        .setCreateTime(createTime).setCreator(creator);
                if(!detail.save())  return false;
            }
            for(OutcomeDetail detail:outcomeDetails){
                detail.setDetailId(service.getPrimaryKey(Constan.SEQ_OUTCOME_DETAIL))
                        .setOrderId(purchaseOrder.getOrderId()).setStatus("1000")
                        .setCreateTime(createTime).setCreator(creator);
                if(!detail.save()) return false;
            }
            return true;
        });

        renderJson(Feedback.success());

    }
}
